function [pop_act]=pop_act_sorted(aux_data,frame_times,ROIs,nbr_frames,draw_fig)
[velP,velM,velP_ind,velM_ind,velP_raw,velM_raw]=get_vel_ind_from_adata(aux_data);
runM=velM_ind;
runP=velP_ind;
stim_id=round(aux_data(3,:)*2);
shutterOpen=find(abs(diff(aux_data(1,:)>1))==1);
if length(nbr_frames)>5
    order=[];
    for xnd=1:length(nbr_frames)
        if nbr_frames(xnd)==20000
            if xnd==length(nbr_frames)
                order(xnd)=3;
            else
                order(xnd)=1;
            end
        else
            order(xnd)=2;
        end
    end
else
    order=[1 2 1 2 3];
end
a=1:length(order);
order(max(a(order==2))+1:end)=3;

nbr_exp=length(order);
nbr_bas=sum(order==3);
bas_exp=[];
for lnd=1:length(nbr_bas)
    bas_exp(lnd)=shutterOpen((nbr_exp*2)-((lnd*2)-1));
end
bas_exp=min(bas_exp);
% lst_pb=shutterOpen(end-(nbr_bas+1));
nbr_cells=0;
for pnd=1:length(ROIs)
    nbr_cells=nbr_cells+size(ROIs{pnd},2);
end
pop_sort_act=zeros(nbr_cells,47);
% av_act=zeros(nbr_cells,1);
cnt=1;
for xnd=1:length(ROIs)
    cur_frame_times=frame_times(xnd:4:end);
%     fst_frm=cur_frame_times(1);
    for cnd=1:length(ROIs{xnd})
        display(['cell ' num2str(cnt) '/' num2str(nbr_cells)])
        act=ftfil(ROIs{xnd}(cnd).activity,18,0,10);
        act=psmooth(act);
        [act_baseline]=baseline_f(act,cur_frame_times,aux_data,velM_ind,nbr_frames,bas_exp);
        raw_act=act/act_baseline;
        raw_act=raw_act-1;
        thresh=det_thresh_for_peak_resp(raw_act);
        raw_act(raw_act<thresh)=0;
        ROI_act=map_ROI_act_to_aux_data(raw_act,cur_frame_times,length(aux_data));
        [output]=sort_act(ROI_act,runM,runP,stim_id,shutterOpen,order);
        pop_sort_act(cnt,:)=output;
        cnt=cnt+1;
    end
end

pop_act=mean(pop_sort_act,1);
if draw_fig==1
    figure;
    ylim([0 max(pop_act)])
    scatter([1:47],pop_act)
end